//
//  MOMyGetMarriedHisEditOrCreatViewController.m
//  MobileOffice
//
//  Created by 冰冰 on 2019/8/16.
//  Copyright © 2019 com.idolmedia. All rights reserved.
//

#import "MOMyGetMarriedHisEditOrCreatViewController.h"
#import "JZGCarSaleImageCellModel.h"
#import "TZImagePickerController.h"
#import "JZGCarSaleImageCellFrame.h"
#import "JZGCarSaleImageCell.h"
#import <Photos/Photos.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import "UIImage+Extension.h"

@interface MOMyGetMarriedHisEditOrCreatViewController ()<UITableViewDelegate,UITableViewDataSource,JZGCarSaleImageCellDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,TZImagePickerControllerDelegate,UIActionSheetDelegate,XLsn0wPickerTimerDelegate,UITextViewDelegate,UITextFieldDelegate>

@property(nonatomic,strong)UITableView *tableView;

@property(nonatomic,strong)NSMutableArray *dataSource;

@property(nonatomic,strong)UIView *headerView;

@property(nonatomic,strong)UITextField *yearOfNumberTextField;

@property(nonatomic,strong)UITextField *dayOfNumberTextField;

@property(nonatomic,strong)UIButton *startTimeButton;

@property(nonatomic,strong)NSString *startTimeStr;

@property(nonatomic,strong)UIButton *endTimeButton;

@property(nonatomic,strong)NSString *endTimeStr;

@property(nonatomic,strong)UITextView *merriedListTextView;

@property(nonatomic,strong)UIView *bottomView;

@property(nonatomic,strong)NSDictionary *dataDic;

@property (nonatomic, strong)JZGCarSaleImageCellFrame *saleImageCellFrame;

@property (nonatomic, strong)JZGCarSaleImageCellModel *saleImageCellModel;

@property (nonatomic, strong)JZGCarSaleImageCellFrame *saleImageCellFrame1;

@property (nonatomic, strong)JZGCarSaleImageCellModel *saleImageCellModel1;

@property (nonatomic, strong)JZGCarSaleImageCellFrame *saleImageCellFrame2;

@property (nonatomic, strong)JZGCarSaleImageCellModel *saleImageCellModel2;

@property (nonatomic, strong)NSMutableArray *photoImageArray;//走访情况上传数组

@property (nonatomic, strong)NSMutableArray *photoImageArray1;//政策情况上传数组

@property (nonatomic, strong)NSMutableArray *photoImageArray2;//联系活动上传数组

@property (nonatomic, assign)NSInteger selectedImageTag;

@end

@implementation MOMyGetMarriedHisEditOrCreatViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self creatView];
    
    [self initData];
    
    [self getDataForView];
    
    if ([self.editOrCreatStatus integerValue]==1) {
        [self getData];
    }
}

-(void)creatView
{
    self.title = @"创建结亲记录";
    
    self.view.backgroundColor = KGrayColor_ededed;
    
    [self.view addSubview:self.tableView];
    self.tableView.tableHeaderView = self.headerView;
    
    [self.view addSubview:self.bottomView];
    
    [self setupImageCellData:self.photoImageArray];
    
    [self setupImageCellData1:self.photoImageArray1];
    
    [self setupImageCellData2:self.photoImageArray2];
    
}

-(void)initData
{
    self.dataSource = [NSMutableArray array];
    [self.tableView reloadData];
}

-(void)getData
{
    NSString *url = [NSString stringWithFormat:@"%@?authorization=%@",RECIPIENTRECORD_GETRECIPIENTRECORDBYID_URL,[NSString URLEncodedString:[MOUser sharedMOUser].token]];
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [PPNetworkHelper POST:url parameters:@{@"id":self.idStr} success:^(id responseObject) {
        NSLog(@"结亲记录详情：%@",responseObject);
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            self.yearOfNumberTextField.text = responseObject[@"batch"];
            self.dayOfNumberTextField.text = responseObject[@"days"];
            self.merriedListTextView.placeholder = @"";
            self.merriedListTextView.text = responseObject[@"summary"];
            self.startTimeStr = responseObject[@"startTime"];
            self.endTimeStr = responseObject[@"endTime"];
            [self.startTimeButton setTitle:self.startTimeStr forState:UIControlStateNormal];
            [self.endTimeButton setTitle:self.endTimeStr forState:UIControlStateNormal];
            
            if ([[NSString passNullForString:responseObject[@"visit"]] rangeOfString:@".jpg"].location!=NSNotFound||[[NSString passNullForString:responseObject[@"visit"]] rangeOfString:@".png"].location!=NSNotFound) {
                NSString *str = [NSString stringWithFormat:@"%@?imgPath=%@",RECIPIENTRECORD_IOREADIMAGE_URL,[NSString URLEncodedString:responseObject[@"visit"]]];

                [PPNetworkHelper GET:str parameters:@{} success:^(id responseObject) {
                    UIImage *image = [UIImage imageWithData:responseObject];
                    CGSize size = image.size;
                    if (size.width==0) {
                        return ;
                    }
                    NSDictionary *dic = @{
                                          @"image":image,
                                          @"imageType":@"jpg",
                                          @"data":responseObject
                                          };
                    [self.photoImageArray addObject:dic];
                    [self setupImageCellData:self.photoImageArray];
                    [self.tableView reloadData];
                    
                } failure:^(NSError *error) {
                    
                }];
            }
            
            if ([[NSString passNullForString:responseObject[@"publicity"]] rangeOfString:@".jpg"].location!=NSNotFound||[[NSString passNullForString:responseObject[@"publicity"]] rangeOfString:@".png"].location!=NSNotFound) {
                NSString *str = [NSString stringWithFormat:@"%@?imgPath=%@",RECIPIENTRECORD_IOREADIMAGE_URL,[NSString URLEncodedString:responseObject[@"publicity"]]];
                
                [PPNetworkHelper GET:str parameters:@{} success:^(id responseObject) {
                    UIImage *image = [UIImage imageWithData:responseObject];
                    CGSize size = image.size;
                    if (size.width==0) {
                        return ;
                    }
                    NSDictionary *dic = @{
                                          @"image":image,
                                          @"imageType":@"jpg",
                                          @"data":responseObject
                                          };
                    [self.photoImageArray1 addObject:dic];
                    [self setupImageCellData1:self.photoImageArray1];
                    [self.tableView reloadData];
                    
                } failure:^(NSError *error) {
                    
                }];
            }
            
            
            if ([[NSString passNullForString:responseObject[@"fellowship"]] rangeOfString:@".jpg"].location!=NSNotFound||[[NSString passNullForString:responseObject[@"fellowship"]] rangeOfString:@".png"].location!=NSNotFound) {
                NSString *str = [NSString stringWithFormat:@"%@?imgPath=%@",RECIPIENTRECORD_IOREADIMAGE_URL,[NSString URLEncodedString:responseObject[@"fellowship"]]];
                
                [PPNetworkHelper GET:str parameters:@{} success:^(id responseObject) {
                    UIImage *image = [UIImage imageWithData:responseObject];
                    CGSize size = image.size;
                    if (size.width==0) {
                        return ;
                    }
                    NSDictionary *dic = @{
                                          @"image":image,
                                          @"imageType":@"jpg",
                                          @"data":responseObject
                                          };
                    [self.photoImageArray2 addObject:dic];
                    [self setupImageCellData2:self.photoImageArray2];
                    [self.tableView reloadData];
                    
                } failure:^(NSError *error) {
                    
                }];
            }
        }
        
    } failure:^(NSError *error) {
        NSLog(@"结亲记录详情：%@",[error localizedDescription]);
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [[ADShowMessage shareShowMessage]showTextOnly:[error localizedDescription] showInView:self.view];
    }];
}

-(void)getDataForView
{
    NSString *url = [NSString stringWithFormat:@"%@?authorization=%@",RECIPIENTPROJECT_GETECIPIENTPROJECTBYMASTERID_URL,[NSString URLEncodedString:[MOUser sharedMOUser].token]];
    
    [PPNetworkHelper POST:url parameters:@{@"masterId":self.masterId} success:^(id responseObject) {
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            self.dataDic = responseObject;
            if ([[NSString passNullForString:responseObject[@"special"]] isEqualToString:@"是"]) {
                self.yearOfNumberTextField.placeholder = @"请选择";
            }else{
                self.yearOfNumberTextField.placeholder = @"请选择";
            }
        }
    } failure:^(NSError *error) {
        
    }];
    
        
}

#pragma mark -- 提交
-(void)clickSubmitButton
{
    if ([self.yearOfNumberTextField.text integerValue]==0) {
        [[ADShowMessage shareShowMessage]showTextOnly:@"记录次数不能为空" showInView:self.view];
        return;
    }
    if ([self.dayOfNumberTextField.text integerValue]==0) {
        [[ADShowMessage shareShowMessage]showTextOnly:@"总计天数不能为空" showInView:self.view];
        return;
    }
    if (self.merriedListTextView.text.length==0) {
        [[ADShowMessage shareShowMessage]showTextOnly:@"结亲记录描述不能为空" showInView:self.view];
        return;
    }
    
    NSString *imageName1 = @"";
    NSString *imageName2 = @"";
    NSString *imageName3 = @"";
    NSMutableArray *imageArr = [NSMutableArray array];
    NSMutableArray *imageNArr = [NSMutableArray array];
    if (self.photoImageArray.count>0) {
        [imageArr addObject:self.photoImageArray[0]];
        imageName1 = [NSString stringWithFormat:@"%@%@%@_%@",@"visit",[self getNowTimeTimestamp3],@"1",@"zoufang.jpg"];
        [imageNArr addObject:[imageName1 stringByReplacingOccurrencesOfString:@".jpg" withString:@""]];
    }
    if(self.photoImageArray1.count>0){
        [imageArr addObject:self.photoImageArray1[0]];
        imageName2 = [NSString stringWithFormat:@"%@%@%@_%@",@"publicity",[self getNowTimeTimestamp3],@"2",@"zhengce.jpg"];
        [imageNArr addObject:[imageName2 stringByReplacingOccurrencesOfString:@".jpg" withString:@""]];
    }
    if(self.photoImageArray2.count>0){
        [imageArr addObject:self.photoImageArray2[0]];
        imageName3 = [NSString stringWithFormat:@"%@%@%@_%@",@"fellowship",[self getNowTimeTimestamp3],@"3",@"huodong.jpg"];
        [imageNArr addObject:[imageName3 stringByReplacingOccurrencesOfString:@".jpg" withString:@""]];
    }
    
    //提交表单数据
    NSString *url = [NSString stringWithFormat:@"%@?authorization=%@",RECIPIENTRECORD_ADDORUPDATERECORD_URL,[NSString URLEncodedString:[MOUser sharedMOUser].token]];
    
    NSMutableDictionary *muDic = [NSMutableDictionary dictionary];
    [muDic setObject:self.merriedListTextView.text forKey:@"summary"];
    [muDic setObject:self.yearOfNumberTextField.text forKey:@"batch"];
    [muDic setObject:[MOUser sharedMOUser].userName forKey:@"userId"];
    [muDic setObject:self.masterId forKey:@"masterId"];
    [muDic setObject:[NSString getCurrentTimesAndFormat:@"YYYY-MM-dd HH:mm"] forKey:@"createTime"];
    [muDic setObject:self.dayOfNumberTextField.text forKey:@"days"];
    [muDic setObject:self.startTimeStr forKey:@"startTime"];
    [muDic setObject:self.endTimeStr forKey:@"endTime"];
    if (imageName1.length>0) {
        [muDic setObject:imageName1 forKey:@"visit"];
    }else{
        [muDic setObject:@"" forKey:@"visit"];
    }
    if (imageName2.length>0) {
        [muDic setObject:imageName2 forKey:@"publicity"];
    }else{
        [muDic setObject:@"" forKey:@"publicity"];
    }
    if (imageName3.length>0) {
        [muDic setObject:imageName3 forKey:@"fellowship"];
    }else{
        [muDic setObject:@"" forKey:@"fellowship"];
    }
    
    if ([self.editOrCreatStatus integerValue]==1) {
        [muDic setObject:self.idStr forKey:@"id"];
    }
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [PPNetworkHelper POST:url parameters:muDic success:^(id responseObject) {
        NSLog(@"结亲记录创建：%@",responseObject);
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if ([responseObject[@"flag"] integerValue]>0) {
            [self.navigationController popViewControllerAnimated:YES];
            [[NSNotificationCenter defaultCenter]postNotificationName:@"hisAction" object:nil];;
            if (self.editOrCreatActionBlock) {
                self.editOrCreatActionBlock();
            }
        }
    } failure:^(NSError *error) {
        NSLog(@"结亲记录创建：%@",[error localizedDescription]);
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [[ADShowMessage shareShowMessage]showTextOnly:[error localizedDescription] showInView:self.view];
    }];
    
    //上传图片
    if (imageArr.count==0) {
        return;
    }
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [PPNetworkHelper uploadImagesWithURL:RECIPIENTRECORD_UPLOADIMG_URL parameters:@{} name:imageNArr images:imageArr fileNames:imageNArr imageScale:0.5 imageType:nil progress:^(NSProgress *progress) {
        
    } success:^(id responseObject) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        NSLog(@"%@",responseObject);
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    }];
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    if (self.dataDic.allKeys.count>0) {
        NSArray *tArr = @[];
        if ([[NSString passNullForString:self.dataDic[@"special"]] isEqualToString:@"是"]) {
            self.yearOfNumberTextField.placeholder = @"请选择";
            tArr = @[@"1",@"2"];
        }else{
            self.yearOfNumberTextField.placeholder = @"请选择";
            tArr = @[@"1",@"2",@"3",@"4",@"5",@"6"];
        }
        
        SNXYSelectedNumberView *pickview = [[SNXYSelectedNumberView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        pickview.numberArray = tArr;
        __weak typeof (self)weakSelf = self;
        pickview.clickIndexBlock = ^(NSInteger index) {
            weakSelf.yearOfNumberTextField.text = tArr[index];
        };
        [WINDOW addSubview:pickview];
        
        return NO;
    }else{
        return YES;
    }
}

-(NSString *)getNowTimeTimestamp3{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss SSS"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    
    //设置时区,这个对于时间的处理有时很重要
    
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    
    [formatter setTimeZone:timeZone];
    
    NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式
    
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[datenow timeIntervalSince1970]*1000];
    
    return timeSp;
}

#pragma mark -- 选择时间
-(void)clickTimeButton:(UIButton *)sender
{
    XLsn0wPickerTimer *pickerDate = [[XLsn0wPickerTimer alloc] init];
    pickerDate.tag = sender.tag;
    pickerDate.maxComponentCount = 3;
    pickerDate.xlsn0wDelegate = self;
    [pickerDate show];
}

- (void)pickerTimer:(XLsn0wPickerTimer *)pickerTimer year:(NSInteger)year month:(NSInteger)month day:(NSInteger)day {
    
    NSString *dateStr = [NSString stringWithFormat:@"%ld-%ld-%ld", (long)year, (long)month, (long)day];
    if (pickerTimer.tag==0) {//开始时间
        self.startTimeStr = dateStr;
        [self.startTimeButton setTitle:dateStr forState:UIControlStateNormal];
        [self.startTimeButton SG_imagePositionStyle:(SGImagePositionStyleRight) spacing:6];
    }else{//结束时间
        self.endTimeStr = dateStr;
        [self.endTimeButton setTitle:dateStr forState:UIControlStateNormal];
        [self.endTimeButton SG_imagePositionStyle:(SGImagePositionStyleRight) spacing:6];
    }
}

- (void)setupImageCellData:(NSMutableArray *)imageArr
{
    NSMutableArray *imageA = [NSMutableArray array];
    for (int i = 0; i<imageArr.count; i++) {
        if ([imageArr[i] isKindOfClass:[UIImage class]]) {
            [imageA addObject:imageArr[i]];
        }else if ([imageArr[i] isKindOfClass:[NSString class]]){
            [imageA addObject:imageArr[i]];
        }
        else{
            [imageA addObject:imageArr[i][@"image"]];
        }
    }
    imageArr = imageA;
    
    JZGCarSaleImageCellModel *saleImageCellModel = [[JZGCarSaleImageCellModel alloc]init];
    saleImageCellModel.maxWidth = SCREEN_WIDTH - 24;
    saleImageCellModel.imageArray = imageArr;
    self.saleImageCellModel = saleImageCellModel;
    
    JZGCarSaleImageCellFrame *saleImageCellFrame = [[JZGCarSaleImageCellFrame alloc]init];
    saleImageCellFrame.totalCount = 1;
    saleImageCellFrame.cellModel = saleImageCellModel;
    self.saleImageCellFrame = saleImageCellFrame;
}

- (void)setupImageCellData1:(NSMutableArray *)imageArr
{
    NSMutableArray *imageA = [NSMutableArray array];
    for (int i = 0; i<imageArr.count; i++) {
        if ([imageArr[i] isKindOfClass:[UIImage class]]) {
            [imageA addObject:imageArr[i]];
        }else if ([imageArr[i] isKindOfClass:[NSString class]]){
            [imageA addObject:imageArr[i]];
        }
        else{
            [imageA addObject:imageArr[i][@"image"]];
        }
    }
    imageArr = imageA;
    
    JZGCarSaleImageCellModel *saleImageCellModel = [[JZGCarSaleImageCellModel alloc]init];
    saleImageCellModel.maxWidth = SCREEN_WIDTH - 24;
    saleImageCellModel.imageArray = imageArr;
    self.saleImageCellModel1 = saleImageCellModel;
    
    JZGCarSaleImageCellFrame *saleImageCellFrame = [[JZGCarSaleImageCellFrame alloc]init];
    saleImageCellFrame.totalCount = 1;
    saleImageCellFrame.cellModel = saleImageCellModel;
    self.saleImageCellFrame1 = saleImageCellFrame;
}

- (void)setupImageCellData2:(NSMutableArray *)imageArr
{
    NSMutableArray *imageA = [NSMutableArray array];
    for (int i = 0; i<imageArr.count; i++) {
        if ([imageArr[i] isKindOfClass:[UIImage class]]) {
            [imageA addObject:imageArr[i]];
        }else if ([imageArr[i] isKindOfClass:[NSString class]]){
            [imageA addObject:imageArr[i]];
        }
        else{
            [imageA addObject:imageArr[i][@"image"]];
        }
    }
    imageArr = imageA;
    
    JZGCarSaleImageCellModel *saleImageCellModel = [[JZGCarSaleImageCellModel alloc]init];
    saleImageCellModel.maxWidth = SCREEN_WIDTH - 24;
    saleImageCellModel.imageArray = imageArr;
    self.saleImageCellModel2 = saleImageCellModel;
    
    JZGCarSaleImageCellFrame *saleImageCellFrame = [[JZGCarSaleImageCellFrame alloc]init];
    saleImageCellFrame.totalCount = 1;
    saleImageCellFrame.cellModel = saleImageCellModel;
    self.saleImageCellFrame2 = saleImageCellFrame;
}

#pragma mark - JZGCarSaleImageCellDelegate
- (void)carSaleImageCellDidClickImageButtonAndCellTag:(NSInteger)cellTag
{
    self.selectedImageTag = cellTag;
    UIActionSheet *imgAction = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"从相册获取", nil];
    [imgAction showInView:self.view];
}

#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex==0)
    {
        [self showCamera];
        
    }else if (buttonIndex==1)
    {
        [self showImagePick];
    }
}

//打开第三方相册
- (void)showImagePick
{
    if (![self judgeIsHavePhotoAblumAuthority]) {
        NSString *appName = [[NSBundle mainBundle].infoDictionary valueForKey:@"CFBundleDisplayName"];
        if (!appName) appName = [[NSBundle mainBundle].infoDictionary valueForKey:@"CFBundleName"];
        NSString *msgStr = [NSString stringWithFormat:@"上传头像服务需要访问您的相册，请在%@的\"设置-隐私-照片\"选项中，\r允许%@访问您的手机相册。",[UIDevice currentDevice].model,appName];
        
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"无法访问相册" message:msgStr preferredStyle:UIAlertControllerStyleAlert];
        
        [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
        [self presentViewController:alertController animated:YES completion:nil];
        return;
    }
    
    NSInteger count = 0;
    if (self.selectedImageTag==0) {
        count = 1 - self.photoImageArray.count;
    }else if (self.selectedImageTag==1){
        count = 1 - self.photoImageArray1.count;
    }else{
        count = 1 - self.photoImageArray2.count;
    }
    TZImagePickerController *imagePickerVc = nil;
    imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:count delegate:self];
    imagePickerVc.isSelectOriginalPhoto = YES;
    // 1.如果你需要将拍照按钮放在外面，不要传这个参数
    imagePickerVc.allowTakePicture = NO; // 在内部显示拍照按钮
    imagePickerVc.allowPickingVideo = NO;
    imagePickerVc.allowPickingImage = YES;
    imagePickerVc.allowPickingOriginalPhoto = NO;
    imagePickerVc.naviTitleColor = KBlackColor_222222;
    imagePickerVc.barItemTextColor = KBlackColor_222222;
    imagePickerVc.sortAscendingByModificationDate = YES;
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        
    }];
    [self presentViewController:imagePickerVc animated:YES completion:nil];
    
}

-(void)showCamera
{
    if (![self judgeIsHaveCameraAuthority]) {
        NSString *appName = [[NSBundle mainBundle].infoDictionary valueForKey:@"CFBundleDisplayName"];
        if (!appName) appName = [[NSBundle mainBundle].infoDictionary valueForKey:@"CFBundleName"];
        NSString *msgStr = [NSString stringWithFormat:@"上传图片服务需要访问您的相机，请在%@的\"设置-隐私\"选项中，\r允许%@访问您的手机相机。",[UIDevice currentDevice].model,appName];
        
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"无法访问相机" message:msgStr preferredStyle:UIAlertControllerStyleAlert];
        
        [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
        [self presentViewController:alertController animated:YES completion:nil];
        return;
    }
    
    //创建UIImagePickerController对象，并设置代理和可编辑
    UIImagePickerController * imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.editing = YES;
    imagePicker.delegate = self;
    imagePicker.allowsEditing = YES;
    
    if ([UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront] || [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear]) {
        //选择相机时，设置UIImagePickerController对象相关属性
        imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        imagePicker.modalPresentationStyle = UIModalPresentationFullScreen;
        imagePicker.mediaTypes = @[(NSString *)kUTTypeImage];
        imagePicker.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
        imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        //跳转到UIImagePickerController控制器弹出相机
        [self presentViewController:imagePicker animated:YES completion:nil];
    }else{
        [[ADShowMessage shareShowMessage]showTextOnly:@"当前设备不支持拍摄" showInView:self.view];
    }
}

- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto {
    [picker dismissViewControllerAnimated:YES completion:nil];
    if (self.selectedImageTag==0) {
        for (int i = 0; i<photos.count; i++) {
            
            UIImage *resultImage = [UIImage compressImageQuality:photos[i] toByte:200];
            
            NSDictionary *dic = @{
                                  @"image":resultImage,
                                  @"imageType":@"jpg",
                                  @"data":UIImageJPEGRepresentation(resultImage, 0.5f)
                                  };
            [self.photoImageArray addObject:dic];
        }
        [self setupImageCellData:self.photoImageArray];
        
//        NSIndexPath *indexPathA = [NSIndexPath indexPathForRow:0 inSection:0];
//        [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPathA,nil] withRowAnimation:UITableViewRowAnimationAutomatic];
        [self.tableView reloadData];
        
    }else if (self.selectedImageTag==1) {
        for (int i = 0; i<photos.count; i++) {
            
            UIImage *resultImage = [UIImage compressImageQuality:photos[i] toByte:200];
            NSDictionary *dic = @{
                                  @"image":resultImage,
                                  @"imageType":@"jpg",
                                  @"data":UIImageJPEGRepresentation(resultImage, 0.5f)
                                  };
            [self.photoImageArray1 addObject:dic];
        }
        [self setupImageCellData1:self.photoImageArray1];
        
//        NSIndexPath *indexPathA = [NSIndexPath indexPathForRow:0 inSection:1];
//        [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPathA,nil] withRowAnimation:UITableViewRowAnimationAutomatic];
        [self.tableView reloadData];
    }else if (self.selectedImageTag==2) {
        for (int i = 0; i<photos.count; i++) {
            
            UIImage *resultImage = [UIImage compressImageQuality:photos[i] toByte:200];
            NSDictionary *dic = @{
                                  @"image":resultImage,
                                  @"imageType":@"jpg",
                                  @"data":UIImageJPEGRepresentation(resultImage, 0.5f)
                                  };
            [self.photoImageArray2 addObject:dic];
        }
        [self setupImageCellData2:self.photoImageArray2];
        
//        NSIndexPath *indexPathA = [NSIndexPath indexPathForRow:0 inSection:2];
//        [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPathA,nil] withRowAnimation:UITableViewRowAnimationAutomatic];
        [self.tableView reloadData];
    }
}

#pragma mark - imagePickerController delegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    UIImage *resultImage = [UIImage compressImageQuality:info[UIImagePickerControllerOriginalImage] toByte:200];
    
    NSDictionary *dic = @{
                          @"image":resultImage,
                          @"imageType":@"jpg",
                          @"data":UIImageJPEGRepresentation(resultImage,0.5f)
                          };
    if (self.selectedImageTag==0) {
        
        [self.photoImageArray addObject:dic];
        [self setupImageCellData:self.photoImageArray];
//        NSIndexPath *indexPathA = [NSIndexPath indexPathForRow:0 inSection:0];
//        [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPathA,nil] withRowAnimation:UITableViewRowAnimationAutomatic];
        [self.tableView reloadData];
        
    }else if (self.selectedImageTag==1) {
        
        [self.photoImageArray1 addObject:dic];
        [self setupImageCellData1:self.photoImageArray1];
//        NSIndexPath *indexPathA = [NSIndexPath indexPathForRow:0 inSection:1];
//        [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPathA,nil] withRowAnimation:UITableViewRowAnimationAutomatic];
        [self.tableView reloadData];
        
    }else{
        
        [self.photoImageArray2 addObject:dic];
        [self setupImageCellData2:self.photoImageArray2];
//        NSIndexPath *indexPathA = [NSIndexPath indexPathForRow:0 inSection:2];
//        [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPathA,nil] withRowAnimation:UITableViewRowAnimationAutomatic];
        [self.tableView reloadData];
        
    }
}

//按取消按钮时候的功能
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - 判断软件是否有相册、相机访问权限
- (BOOL)judgeIsHavePhotoAblumAuthority
{
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    if (status == PHAuthorizationStatusRestricted ||
        status == PHAuthorizationStatusDenied) {
        return NO;
    }
    return YES;
}

- (BOOL)judgeIsHaveCameraAuthority
{
    AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (status == AVAuthorizationStatusRestricted ||
        status == AVAuthorizationStatusDenied) {
        return NO;
    }
    return YES;
}

#pragma mark - 删除图片
-(void)carSaleImageCellDelegateDidDeleteImageWithIndex:(NSInteger)imageIndex andCellTag:(NSInteger)cellTag
{
    if (cellTag==0) {
        
        [self.photoImageArray removeObjectAtIndex:imageIndex];
        [self setupImageCellData:self.photoImageArray];
        
//        NSIndexPath *indexPathA = [NSIndexPath indexPathForRow:0 inSection:0];
//        [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPathA,nil] withRowAnimation:UITableViewRowAnimationAutomatic];
        [self.tableView reloadData];
        
    }else if (cellTag==1) {
        
        [self.photoImageArray1 removeObjectAtIndex:imageIndex];
        
        [self setupImageCellData1:self.photoImageArray1];
        
//        NSIndexPath *indexPathA = [NSIndexPath indexPathForRow:0 inSection:1];
//        [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPathA,nil] withRowAnimation:UITableViewRowAnimationAutomatic];
        [self.tableView reloadData];
        
    }else{
        
        [self.photoImageArray2 removeObjectAtIndex:imageIndex];
        [self setupImageCellData:self.photoImageArray2];
        
//        NSIndexPath *indexPathA = [NSIndexPath indexPathForRow:0 inSection:2];
//        [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPathA,nil] withRowAnimation:UITableViewRowAnimationAutomatic];
        [self.tableView reloadData];
    }
}

- (void)carSaleImageCellDidClickImageButton {
    
}


#pragma mark -- UITableViewDelegate,UITableViewDataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0) {
        JZGCarSaleImageCell *imageCell = [JZGCarSaleImageCell cellWithTableView:tableView];
        imageCell.tag = 0;
        imageCell.allPhotoNumber = 1;
        imageCell.cellFrame = self.saleImageCellFrame;
        imageCell.delegate = self;
        imageCell.backgroundColor = KWhiteColor;
        return imageCell;
    }else if (indexPath.section==1) {
        JZGCarSaleImageCell *imageCell = [JZGCarSaleImageCell cellWithTableView:tableView];
        imageCell.tag = 1;
        imageCell.allPhotoNumber = 1;
        imageCell.cellFrame = self.saleImageCellFrame1;
        imageCell.delegate = self;
        imageCell.backgroundColor = KWhiteColor;
        return imageCell;
    }else{
        JZGCarSaleImageCell *imageCell = [JZGCarSaleImageCell cellWithTableView:tableView];
        imageCell.tag = 2;
        imageCell.allPhotoNumber = 1;
        imageCell.cellFrame = self.saleImageCellFrame2;
        imageCell.delegate = self;
        imageCell.backgroundColor = KWhiteColor;
        return imageCell;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row==0) {
        return self.saleImageCellFrame.imageContainerViewFrame.size.height;
    }else if (indexPath.row==1){
        return self.saleImageCellFrame1.imageContainerViewFrame.size.height;
    }else{
        return self.saleImageCellFrame2.imageContainerViewFrame.size.height + 20;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section==2) {
        return 20;
    }else{
        return 0.00001;
    }
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return kHConversions(54);
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    NSArray *arr = @[@"走访情况上传",@"政策情况上传",@"联系活动上传"];
    
    UIView *backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, kHConversions(54))];
    backView.backgroundColor = KWhiteColor;
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(15, 0, SCREEN_WIDTH - 30, kHConversions(54))];
    label.textColor = KBlackColor_222222;
    label.font = FONT_SIZE(15);
    label.text = arr[section];
    [backView addSubview:label];
    
    return backView;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if (section==2) {
        UIView *backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 20)];
        
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 10)];
        view.backgroundColor = [UIColor whiteColor];
        [backView addSubview:view];
        
        return backView;
    }else{
        return nil;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}

#pragma mark - 设置顶头分割线
-(void)viewDidLayoutSubviews {
    
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 0)];
    }
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)])  {
        if (@available(iOS 8.0, *)) {
            [self.tableView setLayoutMargins:UIEdgeInsetsMake(0, 0, 0, 0)];
        } else {
            // Fallback on earlier versions
        }
    }
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPat{
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        if (@available(iOS 8.0, *)) {
            [cell setLayoutMargins:UIEdgeInsetsMake(0, 0, 0, 0)];
        } else {
            // Fallback on earlier versions
        }
    }
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]){
        [cell setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 0)];
    }
}

- (void)textViewDidChange:(UITextView *)textView
{
    if (textView.text.length >= 300) {
        textView.text = [textView.text substringToIndex:300];
    }
}

#pragma mark -懒加载
-(UITableView *)tableView
{
    if (!_tableView) {
        
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-StatusBarAndNavigationBarHeight - 57 - TabbarSafeBottomMargin) style:UITableViewStyleGrouped];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = KGrayColor_ededed;
        _tableView.showsVerticalScrollIndicator = NO;
        
    }
    return _tableView;
}

-(UIView *)headerView
{
    if (!_headerView) {
        _headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 1)];
        _headerView.backgroundColor = KWhiteColor;
        
        UIView *lineView1 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 10)];
        lineView1.backgroundColor = KGrayColor_ededed;
        [_headerView addSubview:lineView1];
        
        UILabel *yearLabel1 = [[UILabel alloc]initWithFrame:CGRectMake(15, lineView1.bottom, 70, kHConversions(54))];
        yearLabel1.text = @"本年第";
        yearLabel1.textColor = KBlackColor_222222;
        yearLabel1.font = FONT_SIZE(15);
        [_headerView addSubview:yearLabel1];
        
        self.yearOfNumberTextField = [[UITextField alloc]initWithFrame:CGRectMake(yearLabel1.right + 10, yearLabel1.y, kWConversions(120), kHConversions(54))];
        self.yearOfNumberTextField.textAlignment = NSTextAlignmentCenter;
        self.yearOfNumberTextField.font = FONT_SIZE(15);
        self.yearOfNumberTextField.placeholder = @"请输入次数";
        self.yearOfNumberTextField.keyboardType = UIKeyboardTypeNumberPad;
        self.yearOfNumberTextField.textColor = KBlackColor_222222;
        self.yearOfNumberTextField.font = FONT_SIZE(15);
        self.yearOfNumberTextField.tag = 100;
        self.yearOfNumberTextField.delegate = self;
        [_headerView addSubview:self.yearOfNumberTextField];
        
        UILabel *yearLabel2 = [[UILabel alloc]initWithFrame:CGRectMake(self.yearOfNumberTextField.right + 10, lineView1.bottom, 20, kHConversions(54))];
        yearLabel2.text = @"次";
        yearLabel2.textColor = KBlackColor_222222;
        yearLabel2.font = FONT_SIZE(15);
        [_headerView addSubview:yearLabel2];
        
        UIView *lineView2 = [[UIView alloc]initWithFrame:CGRectMake(0, yearLabel2.bottom, SCREEN_WIDTH, 1)];
        lineView2.backgroundColor = KGrayColor_ededed;
        [_headerView addSubview:lineView2];
        
        CGFloat buttonW = (SCREEN_WIDTH - 30)/2;
        NSArray *arr = @[@"开始时间",@"结束时间"];
        for (int i = 0; i<2; i++) {
            UIButton *backButton = [[UIButton alloc]initWithFrame:CGRectMake(15+buttonW*i, lineView2.bottom + 20, buttonW, 50)];
            backButton.tag = i;
            [backButton addTarget:self action:@selector(clickTimeButton:) forControlEvents:UIControlEventTouchUpInside];
            [_headerView addSubview:backButton];
            
            UILabel *timeLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, backButton.width, 16)];
            timeLabel.textColor = KBlackColor_222222;
            timeLabel.font = FONT_SIZE(15);
            timeLabel.text = arr[i];
            [backButton addSubview:timeLabel];
            
            UIButton *timeButton = [[UIButton alloc]initWithFrame:CGRectMake(0, timeLabel.bottom + 18, buttonW, 16)];
            timeButton.titleLabel.font = FONT_SIZE(15);
            [timeButton setTitleColor:KBlackColor_222222 forState:UIControlStateNormal];
            [timeButton setTitle:[NSString getCurrentTimesAndFormat:@"YYYY-MM-dd"] forState:UIControlStateNormal];
            [timeButton setImage:IMAGE(@"right_notice") forState:UIControlStateNormal];
            [timeButton setContentHorizontalAlignment:(UIControlContentHorizontalAlignmentLeft)];
            [timeButton SG_imagePositionStyle:(SGImagePositionStyleRight) spacing:6];
            [backButton addSubview:timeButton];
            timeButton.tag = i;
            [timeButton addTarget:self action:@selector(clickTimeButton:) forControlEvents:UIControlEventTouchUpInside];
            self.startTimeStr = [NSString getCurrentTimesAndFormat:@"YYYY-MM-dd"];
            self.endTimeStr = [NSString getCurrentTimesAndFormat:@"YYYY-MM-dd"];
            if (i==0) {
                self.startTimeButton = timeButton;
            }else{
                self.endTimeButton = timeButton;
            }
        }
        
        UIView *lineView3 = [[UIView alloc]initWithFrame:CGRectMake(0, lineView2.bottom + 40 + 50, SCREEN_WIDTH, 1)];
        lineView3.backgroundColor = KGrayColor_ededed;
        [_headerView addSubview:lineView3];
        
        UILabel *dayLabel1 = [[UILabel alloc]initWithFrame:CGRectMake(15, lineView3.bottom, 70, kHConversions(54))];
        dayLabel1.text = @"总计天数";
        dayLabel1.textColor = KBlackColor_222222;
        dayLabel1.font = FONT_SIZE(15);
        [_headerView addSubview:dayLabel1];
        
        self.dayOfNumberTextField = [[UITextField alloc]initWithFrame:CGRectMake(dayLabel1.right + 10, dayLabel1.y, kWConversions(120), kHConversions(54))];
        self.dayOfNumberTextField.textAlignment = NSTextAlignmentCenter;
        self.dayOfNumberTextField.font = FONT_SIZE(15);
        self.dayOfNumberTextField.placeholder = @"请输入天数";
        self.dayOfNumberTextField.keyboardType = UIKeyboardTypeNumberPad;
        self.dayOfNumberTextField.textColor = KBlackColor_222222;
        self.dayOfNumberTextField.font = FONT_SIZE(15);
        self.dayOfNumberTextField.tag = 200;
        self.dayOfNumberTextField.delegate = self;
        [_headerView addSubview:self.dayOfNumberTextField];
        
        UILabel *dayLabel2 = [[UILabel alloc]initWithFrame:CGRectMake(self.dayOfNumberTextField.right + 10, lineView3.bottom, 20, kHConversions(54))];
        dayLabel2.text = @"天";
        dayLabel2.textColor = KBlackColor_222222;
        dayLabel2.font = FONT_SIZE(15);
        [_headerView addSubview:dayLabel2];
        
        
        UIView *lineView4 = [[UIView alloc]initWithFrame:CGRectMake(0, dayLabel2.bottom, SCREEN_WIDTH, 10)];
        lineView4.backgroundColor = KGrayColor_ededed;
        [_headerView addSubview:lineView4];
        
        UILabel *listLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, lineView4.bottom + 20, SCREEN_WIDTH - 30, 16)];
        listLabel.text = @"结亲记录";
        listLabel.textColor = KBlackColor_222222;
        listLabel.font = FONT_SIZE(15);
        [_headerView addSubview:listLabel];
        
        self.merriedListTextView = [[UITextView alloc]initWithFrame:CGRectMake(10, listLabel.bottom, SCREEN_WIDTH - 20, 90)];
        self.merriedListTextView.delegate = self;
        self.merriedListTextView.textColor = KBlackColor_222222;
        self.merriedListTextView.font = FONT_SIZE(13);
        self.merriedListTextView.placeholder = @"具体描述，最多300字";
        [_headerView addSubview:self.merriedListTextView];
        
        UIView *lineView5 = [[UIView alloc]initWithFrame:CGRectMake(0, self.merriedListTextView.bottom + 20, SCREEN_WIDTH, 10)];
        lineView5.backgroundColor = KGrayColor_ededed;
        [_headerView addSubview:lineView5];
        
        _headerView.height = lineView5.bottom;
    }
    return _headerView;
}

-(UIView *)bottomView
{
    if (!_bottomView) {
        _bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT - StatusBarAndNavigationBarHeight - TabbarSafeBottomMargin - 57, SCREEN_WIDTH, 57)];
        _bottomView.backgroundColor = KWhiteColor;
        
        UIButton *submitButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, _bottomView.width, _bottomView.height)];
        [submitButton setTitle:@"提交" forState:UIControlStateNormal];
        [submitButton setTitleColor:KBlueColor_2C94FF forState:UIControlStateNormal];
        submitButton.titleLabel.font = FONT_SIZE(15);
        [submitButton addTarget:self action:@selector(clickSubmitButton) forControlEvents:UIControlEventTouchUpInside];
        [_bottomView addSubview:submitButton];
        
        UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 1)];
        lineView.backgroundColor = KGrayColor_ededed;
        [_bottomView addSubview:lineView];
    }
    return _bottomView;
}

- (NSMutableArray *)photoImageArray{
    if (_photoImageArray == nil) {
        _photoImageArray = [NSMutableArray array];
    }
    return _photoImageArray;
}

- (NSMutableArray *)photoImageArray1{
    if (_photoImageArray1 == nil) {
        _photoImageArray1 = [NSMutableArray array];
    }
    return _photoImageArray1;
}

- (NSMutableArray *)photoImageArray2{
    if (_photoImageArray2 == nil) {
        _photoImageArray2 = [NSMutableArray array];
    }
    return _photoImageArray2;
}





@end
